<template>
  <div class="system_role">
    <!--权限系统&ndash;&gt;角色管理-->
    <div class="search">
      <el-form ref="form" :inline="true" :model="form" class="users_search"  :rules="rules">
        <el-form-item :label="$t('system.role')"><!--角色-->
          <el-input prefix-icon="el-icon-search" v-model="form.name" :placeholder="$t('verify.plsInput')" class="inputPhone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch" icon="search">{{ $t('common.search') }}</el-button>
        </el-form-item>
      </el-form><!--end form-->
      <el-button @click="addAccountShow" type="primary">{{ $t('system.addRole') }}</el-button><!--新增角色-->
    </div>

    <div class="data_list">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="left" label="ID" prop="id">ID</el-table-column>
        <el-table-column align="left" :label="$t('system.roleName')" prop="name"><!--角色名-->
          <template slot-scope="scope">
            <span v-if="scope.row.cnName">{{ scope.row.cnName }}</span>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" :label="$t('system.resourceAuth')"><!--资源授权-->
          <template slot-scope="scope">
            <el-button @click="getResourceById(scope.row)" type="text" size="small">{{ $t('system.bindingResource') }}</el-button><!--绑定资源-->
          </template>
        </el-table-column>
      </el-table><!--end table-->
    </div>
    <div class="data_page">
      <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
    </div>

    <!--绑定资源start-->
    <alert-dialog :title="$t('system.bindingResource')" :visible.sync="bindResourceDialogShow" width="500px">
      <el-form class="role_form" :model="roleForm" label-position="top">
        <el-form-item :label="$t('system.roleName')"><!--角色名称-->
          <el-input v-model="roleForm.userName" type="text" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item :label="$t('system.resourceList')"><!--资源列表-->
          <el-tree ref="tree" :data="resourceList" show-checkbox node-key="id" :default-checked-keys="roleForm.checkedRes" :props="defaultProps">资源列表</el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="bindResConfirm" type="primary">{{ $t('system.binding') }}</el-button><!--绑定-->
        <el-button @click="bindResourceDialogShow = false" type="default">{{ $t('common.cancel') }}</el-button>
      </div>
    </alert-dialog>
    <!--绑定资源end-->
    <!--新增角色start-->
    <alert-dialog :title="$t('system.addRole')" :visible.sync="addAccountDialogShow" width="416px">
      <el-form :model="accountForm" :rules="accountRules" ref="accountForm" label-position="top">
        <el-form-item :label="$t('system.roleName')" prop="userName"><!--角色名称-->
          <el-input v-model="accountForm.userName" type="text"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addAccount" type="primary">{{ $t('common.confirm') }}</el-button>
        <el-button @click="closeAccountDialog" type="default">{{ $t('common.cancel') }}</el-button>
      </div>
    </alert-dialog>
    <!--新增角色end-->
  </div>
</template>

<script>
  import Pagination from '@/components/pagination';
  import mixin from '@/service/mixin';
  import AlertDialog from '@/components/alert-dialog';

  export default {
    name: 'systemAccount',
    components: {
      Pagination,
      AlertDialog
    },
    mixins: [mixin],
    data() {
      return {
        form: {
          name: ''
        },
        rules: {},
        bindResourceDialogShow: false,
        roleForm: {
          userId: '',
          userName: '',
          checkedRes: []
        },
        resourceList: [],
        addAccountDialogShow: false,
        accountForm: {
          userName: '',
          type: ''
        },
        accountRules: {
          userName: [
            { required: true, message: this.$t('verify.plsInput'), trigger: 'blur' }
          ]
        }
      };
    },
    computed: {
      defaultProps() {
        return {
          children: 'children',
          // label: this.$root.local === 'zhCN' ? 'cnName' : 'name'
          label: 'cnName',
        };
      },
    },
    methods: {
      getTableData(page = this.page) {
        const params = {
          name: this.form.name,
          pageNum: page.currentPage,
          pageSize: this.page.pageSize
        };
        this.$api.systemManage.getRoleList(params).then((res) => {
          // console.log(res);
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            this.tableData = data.roleList || [];
            this.page.recordsTotal = data.total;
              this.page.currentPage = page.currentPage;
          }
        });
      },
      getResourceList() {
        this.roleForm.checkedRes = [];
        this.$api.systemManage.getResourceTree().then((res) => {
          // console.log(res);
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            if (data) {
              this.resourceList = data;
            }
          }
        });
      },
      getResourceById(row) {
        // 根据Id查询对应的资源
        const params = {
          roleId: row.id
        };
        this.roleForm.userName = row.name;
        this.roleForm.roleId = row.id;
        this.$api.systemManage.getResourceIdListByRoleId(params).then((res) => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            this.bindResourceDialogShow = true;
            if (data instanceof Array) {
              this.roleForm.checkedRes = Object.assign([], data);
              this.$nextTick(() => {
                // 设置选中项
                this.$refs.tree.setCheckedKeys(this.roleForm.checkedRes);
              });
            }
          }
        });
      },
      onSearch() {
        this.page.currentPage = 1;
        this.getTableData();
      },
      bindResConfirm() {
        const params = {
          roleId: this.roleForm.roleId,
          resourceIdList: this.$refs.tree.getCheckedKeys()
        };
        this.$api.systemManage.editRoleResource(params).then((res) => {
          const { status, error } = res;
          if ('1' === status && error === '00000000') {
            this.bindResourceDialogShow = false;
            this.$message.success(this.$t('common.successfulOperation'));
          }
        });
      },
      delAccount(row) {
        // 删除用户
        const params = {
          id: row.id
        };
        this.$confirm(this.$t('system.isConfirmDelete')).then(() => {
          this.$api.systemManage.deleteRole(params).then((res) => {
            const { status, error } = res;
            if ('1' === status && error === '00000000') {
              this.$message.success(this.$t('common.successfulOperation'));
              this.page.currentPage = 1;
              this.getTableData();
            }
          });
        }).catch((e) => {
          // eslint-disable-next-line
          console.log(e);
        });
      },
      addAccountShow() {
        this.addAccountDialogShow = true;
        this.$nextTick(() => {
          this.$refs.accountForm.resetFields();
        });
      },
      addAccount() {
        // 新增用户
        this.accountForm.userName = this.accountForm.userName.trim();
        const params = {
          name: this.accountForm.userName
        };
        this.$refs.accountForm.validate((value) => {
          if (value) {
            this.$api.systemManage.addRole(params).then((res) => {
              const { status, error } = res;
              if ('1' === status && error === '00000000') {
                this.$message.success(this.$t('common.successfulOperation'));
                this.page.currentPage = 1;
                this.getTableData();
                this.$refs.accountForm.resetFields();
                this.addAccountDialogShow = false;
              }
            });
          }
        });
      },
      closeAccountDialog() {
        this.$refs.accountForm.resetFields();
        this.addAccountDialogShow = false;
      }
    },
    created() {
      this.getTableData();
      this.getResourceList();
    }
  };
</script>

<style lang="scss" scoped>
  .inputPhone {
    width: 265px;
  }
  .search{
    background-color: #fff;
    padding: 22px 40px 0;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }
  .data_list{
    background-color: #fff;
    margin: 16px 24px;
    padding: 10px 16px;
  }
  .btn{
    margin-right: 15px;
  }
  .btn_red{
    border-color: #d9415c;
    color: #d9415c;
  }
  .role_form{
    /*padding: 0 16px;*/
  }
  .account_form_type{
    width: 100%;
  }
</style>
